var $Xrm;
(function ($Xrm) {
    var _string = (function () {
        function _string() { }
        _string.isGuid = function isGuid(value) {
            return /[a-z0-9]{8}(?:-[a-z0-9]{4}){3}-[a-z0-9]{12}/i.test(value);
        };
        _string.isNumber = function isNumber(value) {
            return /^\d+$/.test(value);
        };
        _string.format = function format() {
            var args = [];
            for (var _i = 0; _i < (arguments.length - 0); _i++) {
                args[_i] = arguments[_i + 0];
            }
            // avoid crappy string concats and use this method to keep things looking nice
            var s = args[0];
            for(var i = 0; i < args.length - 1; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "gm");
                s = s.replace(reg, args[i + 1]);
            }
            return s;
        };
        _string.insert = function insert(s, position, value) {
            return s.substring(0, position) + value + s.substring(position);
        };
        _string.pad = function pad(value, length) {
            value = String(value);
            length = length || 2;
            while(value.length < length) {
                value = "0" + value;
            }
            return value;
        };
        return _string;
    })();
    $Xrm._string = _string;    
    var _array = (function () {
        function _array() { }
        _array.getLength = function getLength(array) {
            // need this because js objects are strange, .length doesnt work if you use a string indexer since js treats it as a property/object on the object itself
            var count = 0;
            for(var field in array) {
                count++;
            }
            return count;
        };
        _array.joinWithFormat = function joinWithFormat(array, format) {
            var result = "";
            for(var i = 0; i < array.length; i++) {
                result += _string.format(format, array[i]);
            }
            return result;
        };
        return _array;
    })();
    $Xrm._array = _array;    
    var _xml = (function () {
        function _xml() { }
        _xml.getText = function getText(node) {
            return node != undefined ? (node.text !== undefined ? node.text : node.textContent) : null;// cross browser support
            
        };
        _xml.getValue = function getValue(node) {
            // cross browser support, returns any type so we can determine type later if needed
            var value = node.text !== undefined ? node.text : node.textContent;
            // hacky methods to figure out data types
            if(value == "true" || value == "false") {
                return value == "true";
            } else if(_string.isNumber(value)) {
                return parseInt(value);
            }
            return value;
        };
        _xml.getChildNode = // no xpath support for cross browser so here's a poor mans approach
        function getChildNode(node, nodeName) {
            for(var i = 0; i < node.childNodes.length; i++) {
                var childNode = node.childNodes[i];
                if(childNode.nodeName === nodeName) {
                    return childNode;
                }
            }
            return null;
        };
        _xml.getAttribute = function getAttribute(node, attributeName) {
            for(var i = 0; i < node.attributes.length; i++) {
                if(node.attributes[i].nodeName == attributeName) {
                    return node.attributes[i];
                }
            }
            return null;
        };
        _xml.stripNamespace = function stripNamespace(nodeName) {
            // makes it easier to compare/generate dynamic objects without the ugly looking namespaces
            if(nodeName.indexOf(":") > -1) {
                return nodeName.substring(nodeName.indexOf(":") + 1);
            }
            return nodeName;
        };
        return _xml;
    })();
    $Xrm._xml = _xml;    
    var _date = (function () {
        function _date() { }
        _date.format = // this is not a complete dateformatter, you'll see some format parameters dont exist, this was built to handle crm webservice datetime along with few other scenarios
        function format(date, mask) {
            var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMs])\1?|[LloSZ]|"[^"]*"|'[^']*'/g;
            var _ = "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = date.getTimezoneOffset(), flags = {
                d: d,
                dd: _string.pad(d),
                m: m + 1,
                mm: _string.pad(m + 1),
                yy: String(y).slice(2),
                yyyy: y,
                h: H % 12 || 12,
                hh: _string.pad(H % 12 || 12),
                H: H,
                HH: _string.pad(H),
                M: M,
                MM: _string.pad(M),
                s: s,
                ss: _string.pad(s),
                l: _string.pad(L, 3),
                L: _string.pad(L, 7),
                t: H < 12 ? "a" : "p",
                tt: H < 12 ? "am" : "pm",
                T: H < 12 ? "A" : "P",
                TT: H < 12 ? "AM" : "PM",
                o: (o > 0 ? "-" : "+") + _string.insert(_string.pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), 2, ":"),
                S: [
                    "th", 
                    "st", 
                    "nd", 
                    "rd"
                ][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };
            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
            });
        };
        return _date;
    })();
    $Xrm._date = _date;    
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    var Entity = (function () {
        function Entity(logicalName, id) {
            this.LogicalName = logicalName;
            this.Id = id;
        }
        Entity.prototype.GetAttributeValue = function (attributeLogicalName) {
            if(this[attributeLogicalName] != null) {
                return this[attributeLogicalName];
            }
            return null;
        };
        return Entity;
    })();
    $Xrm.Entity = Entity;    
    var EntityReference = (function () {
        function EntityReference(logicalName, id) {
            this.LogicalName = logicalName;
            this.Id = id;
        }
        return EntityReference;
    })();
    $Xrm.EntityReference = EntityReference;    
    var Money = (function () {
        function Money(value) {
            this.Value = value;
        }
        return Money;
    })();
    $Xrm.Money = Money;    
    var OptionSetValue = (function () {
        function OptionSetValue(value) {
            this.Value = value;
        }
        return OptionSetValue;
    })();
    $Xrm.OptionSetValue = OptionSetValue;    
    var FetchExpression = (function () {
        function FetchExpression(query) {
            this.Query = query;
        }
        return FetchExpression;
    })();
    $Xrm.FetchExpression = FetchExpression;    
    var EntityMetadata = (function () {
        function EntityMetadata() {
        }
        EntityMetadata.prototype.get = function (index) {
            if(this[index] != null) {
                return this[index];
            }
            return null;
        };
        return EntityMetadata;
    })();
    $Xrm.EntityMetadata = EntityMetadata;    
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../helpers.ts" />
    /// <reference path="../types.ts" />
    // todo: need a better way to handle this xml building and namespace handing, too ugly and hard to maintain...
    (function (Messages) {
        var OrganizationRequest = (function () {
            // default to A unless stated otherwise
            function OrganizationRequest(requestName, requestNamespace) {
                this._requestNamespace = "a";
                this.RequestName = requestName;
                this.Parameters = [];
                if(requestNamespace != null && requestName != undefined) {
                    this._requestNamespace = requestNamespace;
                }
            }
            OrganizationRequest.XmlNamespaces = {
                "a": "http://schemas.microsoft.com/xrm/2011/Contracts",
                "b": "http://schemas.microsoft.com/crm/2011/Contracts",
                "c": "http://schemas.datacontract.org/2004/07/System.Collections.Generic",
                "i": "http://www.w3.org/2001/XMLSchema-instance",
                "metadata": "http://schemas.microsoft.com/xrm/2011/Metadata"
            };
            OrganizationRequest.prototype.GetResponse = function (responseXml) {
                return new OrganizationResponse();
            };
            OrganizationRequest.prototype.ToSoapXml = function () {
                var xml = $Xrm._string.format("<request i:type=\"{0}:{1}Request\" xmlns:a=\"{2}\" xmlns:b=\"{3}\">", this._requestNamespace, this.RequestName, OrganizationRequest.XmlNamespaces["a"], OrganizationRequest.XmlNamespaces["b"]);
                xml += this.BuildParameterSoapXml();
                if(this.RequestId != null && this.RequestName != undefined) {
                    xml += $Xrm._string.format("<a:RequestId>{0}</a:RequestId>", this.RequestId);
                } else {
                    xml += "<a:RequestId i:nil=\"true\" />";
                }
                xml += $Xrm._string.format("<a:RequestName>{0}</a:RequestName></request>", this.RequestName);
                return xml;
            };
            OrganizationRequest.prototype.BuildParameterSoapXml = function () {
                var xml = $Xrm._string.format("<a:Parameters xmlns:c=\"{0}\"", OrganizationRequest.XmlNamespaces["c"]);
                if($Xrm._array.getLength(this.Parameters) > 0) {
                    xml += ">"// this is not a mistake, if we have parameters we'll append closing element and add the keys, otherwise we'll append /> and self close
                    ;
                    for(var key in this.Parameters) {
                        var value = this.Parameters[key];
                        xml += "<a:KeyValuePairOfstringanyType>";
                        xml += $Xrm._string.format("<c:key>{0}</c:key>", key);
                        xml += this.BuildParameterValue(key, value);
                        xml += "</a:KeyValuePairOfstringanyType>";
                    }
                    xml += "</a:Parameters>";
                } else {
                    xml += " />";
                }
                return xml;
            };
            OrganizationRequest.prototype.BuildEntityParameters = function (value, valueXml) {
                if($Xrm._array.getLength(value) > 0) {
                    valueXml += "<a:Attributes>";
                    for(var attribute in value) {
                        // skip known internal properties. these are useful to the user but has to be ignored when being serialized
                        if(attribute == "LogicalName" || attribute == "Id" || attribute == "get" || attribute == "GetAttributeValue") {
                            continue;
                        }
                        var innerValue = value[attribute];
                        valueXml += $Xrm._string.format("<a:KeyValuePairOfstringanyType><c:key>{0}</c:key>", attribute);
                        valueXml += this.BuildParameterValue(attribute, innerValue);
                        valueXml += "</a:KeyValuePairOfstringanyType>";
                    }
                    valueXml += "</a:Attributes>";
                } else {
                    valueXml += "<a:Attributes i:nil=\"true\" />";
                }
                // todo: check if entitystate element is required on all requests
                valueXml += $Xrm._string.format("<a:EntityState i:nil=\"true\" /><a:FormattedValues /><a:Id>{0}</a:Id><a:LogicalName>{1}</a:LogicalName><a:RelatedEntities />", value.Id != null && value.Id != undefined ? value.Id : "00000000-0000-0000-0000-000000000000", value.LogicalName);
                return valueXml;
            };
            OrganizationRequest.prototype.BuildParameterValue = function (key, value) {
                var type = "";
                var valueXml = "";
                var additionalNS = "";
                if(value instanceof $Xrm.Entity) {
                    type = "a:Entity";
                    valueXml = this.BuildEntityParameters(value, valueXml);
                } else if(value instanceof $Xrm.EntityReference) {
                    type = "a:EntityReference";
                    valueXml = this.BuildEntityReferenceValueParameter(value);
                } else if(value instanceof $Xrm.FetchExpression) {
                    type = "a:FetchExpression";
                    valueXml = $Xrm._string.format("<a:Query>{0}</a:Query>", value.Query);
                } else if(value instanceof $Xrm.OptionSetValue) {
                    type = "a:OptionSetValue";
                    valueXml = $Xrm._string.format("<a:Value>{0}</a:Value>", value.Value);
                } else if(key == "ColumnSet") {
                    // we need to fuck around with allcolumns=true/false and columnset...
                    type = "a:ColumnSet";
                    valueXml = $Xrm._string.format("<a:AllColumns>{0}</a:AllColumns>", value.constructor == Boolean ? value : false);
                    valueXml += "<a:Columns xmlns:z=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"";
                    if(value.constructor == Boolean && value) {
                        // if it's all columns; selfclose and be done
                        valueXml += " />";
                    } else {
                        valueXml += $Xrm._string.format(">{0}</a:Columns>", $Xrm._array.joinWithFormat(value, "<z:string>{0}</z:string>"));
                    }
                } else if(key == "EntityFilters") {
                    type = "metadata:EntityFilters";
                    additionalNS = $Xrm._string.format(" xmlns:metadata=\"{0}\"", OrganizationRequest.XmlNamespaces["metadata"]);
                    valueXml = value;
                } else if(value instanceof $Xrm.Money) {
                    type = "a:Money";
                    valueXml = $Xrm._string.format("<a:Value>{0}</a:Value>", value.Value);
                } else if(value instanceof $Xrm.OptionSetValue) {
                    type = "a:OptionSetValue";
                    valueXml = $Xrm._string.format("<a:Value>{0}</a:Value>", value.Value);
                } else if(value instanceof $Xrm.EntityReference) {
                    type = "a:EntityReference";
                    valueXml = this.BuildEntityReferenceValueParameter(value);
                } else if($Xrm._string.isGuid(value)) {
                    type = "z:guid";
                    additionalNS = " xmlns:z=\"http://schemas.microsoft.com/2003/10/Serialization/\"";
                    valueXml = value;
                } else {
                    // todo: cleanup; too difficult to maintain this condensed if/else
                    type = value instanceof Date ? "dateTime" : value.constructor == String ? "string" : value.constructor == Boolean ? "boolean" : (typeof value === 'number' && value % 1 == 0) ? "int" : (/^(\d+\.?\d{0,9}|\.\d{1,9})$/.test(value)) ? "decimal" : "";
                    if(type != "") {
                        type = "z:" + type;
                        additionalNS = " xmlns:z=\"http://www.w3.org/2001/XMLSchema\"";
                        valueXml = value instanceof Date ? $Xrm._date.format(value, "yyyy-mm-ddTHH:MM:ss.Lo") : value;
                    }
                }
                return $Xrm._string.format("<c:value i:type=\"{0}\"{1}>{2}</c:value>", type, additionalNS, valueXml);
            };
            OrganizationRequest.prototype.BuildEntityReferenceValueParameter = function (value) {
                var valueXml = $Xrm._string.format("<a:Id>{0}</a:Id><a:LogicalName>{1}</a:LogicalName>", value.Id, value.LogicalName);
                if(value.Name != null && value.Name != undefined) {
                    valueXml += $Xrm._string.format("<a:Name></a:Name>", value.Name);
                } else {
                    valueXml += "<a:Name i:nil=\"true\" />";
                }
                return valueXml;
            };
            return OrganizationRequest;
        })();
        Messages.OrganizationRequest = OrganizationRequest;        
        var OrganizationResponse = (function () {
            function OrganizationResponse(responseName, responseXml) {
                this.ResponseName = responseName;
                this.Results = [];
                if(responseXml != null && responseXml != undefined) {
                    this.ParseResponse(responseXml);
                }
            }
            OrganizationResponse.prototype.BindProperties = function () {
            };
            OrganizationResponse.prototype.ParseResponse = function (responseXml) {
                var rn = $Xrm._xml.getChildNode(responseXml.firstChild.firstChild.firstChild.firstChild, 'a:Results');
                if(rn != null) {
                    for(var i = 0; i < rn.childNodes.length; i++) {
                        var current = rn.childNodes[i];
                        var key = $Xrm._xml.getText(current.childNodes[0]);
                        var value = $Xrm._xml.getText(current.childNodes[1]);
                        this.Results[key] = value;
                    }
                }
            };
            return OrganizationResponse;
        })();
        Messages.OrganizationResponse = OrganizationResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var AssignRequest = (function (_super) {
            __extends(AssignRequest, _super);
            function AssignRequest() {
                        _super.call(this, "Assign", "b")// namespace is 'b' because this request is from crm4 days
                ;
                this.Assignee = null;
                this.Target = null;
            }
            AssignRequest.prototype.GetResponse = function (responseXml) {
                return new AssignResponse(responseXml);
            };
            AssignRequest.prototype.ToSoapXml = function () {
                this.Parameters["Target"] = this.Target;
                this.Parameters["Assignee"] = this.Assignee;
                return _super.prototype.ToSoapXml.call(this);
            };
            return AssignRequest;
        })(Messages.OrganizationRequest);
        Messages.AssignRequest = AssignRequest;        
        var AssignResponse = (function (_super) {
            __extends(AssignResponse, _super);
            function AssignResponse(responseXml) {
                        _super.call(this, "Assign", responseXml);
            }
            return AssignResponse;
        })(Messages.OrganizationResponse);
        Messages.AssignResponse = AssignResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var AssociateEntitiesRequest = (function (_super) {
            __extends(AssociateEntitiesRequest, _super);
            function AssociateEntitiesRequest() {
                        _super.call(this, "AssociateEntities", "b")// namespace is 'b' because this request is from crm4 days
                ;
                this.Moniker1 = null;
                this.Moniker2 = null;
                this.RelationshipName = null;
            }
            AssociateEntitiesRequest.prototype.GetResponse = function (responseXml) {
                return new AssociateEntitiesResponse(responseXml);
            };
            AssociateEntitiesRequest.prototype.ToSoapXml = function () {
                this.Parameters["Moniker1"] = this.Moniker1;
                this.Parameters["Moniker2"] = this.Moniker2;
                this.Parameters["RelationshipName"] = this.RelationshipName;
                return _super.prototype.ToSoapXml.call(this);
            };
            return AssociateEntitiesRequest;
        })(Messages.OrganizationRequest);
        Messages.AssociateEntitiesRequest = AssociateEntitiesRequest;        
        var AssociateEntitiesResponse = (function (_super) {
            __extends(AssociateEntitiesResponse, _super);
            function AssociateEntitiesResponse(responseXml) {
                        _super.call(this, "AssociateEntities", responseXml);
            }
            return AssociateEntitiesResponse;
        })(Messages.OrganizationResponse);
        Messages.AssociateEntitiesResponse = AssociateEntitiesResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var CreateRequest = (function (_super) {
            __extends(CreateRequest, _super);
            function CreateRequest() {
                        _super.call(this, "Create");
                this.Target = null;
            }
            CreateRequest.prototype.GetResponse = function (responseXml) {
                return new CreateResponse(responseXml);
            };
            CreateRequest.prototype.ToSoapXml = function () {
                this.Parameters["Target"] = this.Target;
                return _super.prototype.ToSoapXml.call(this);
            };
            return CreateRequest;
        })(Messages.OrganizationRequest);
        Messages.CreateRequest = CreateRequest;        
        var CreateResponse = (function (_super) {
            __extends(CreateResponse, _super);
            function CreateResponse(responseXml) {
                        _super.call(this, "Create", responseXml);
                this.BindProperties();
            }
            CreateResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.Id = this.Results["id"]// interesting that this parameter is lowercase...
                ;
            };
            return CreateResponse;
        })(Messages.OrganizationResponse);
        Messages.CreateResponse = CreateResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var DisassociateEntitiesRequest = (function (_super) {
            __extends(DisassociateEntitiesRequest, _super);
            function DisassociateEntitiesRequest() {
                        _super.call(this, "DisassociateEntities", "b")// namespace is 'b' because this request is from crm4 days
                ;
                this.Moniker1 = null;
                this.Moniker2 = null;
                this.RelationshipName = null;
            }
            DisassociateEntitiesRequest.prototype.GetResponse = function (responseXml) {
                return new DisassociateEntitiesResponse(responseXml);
            };
            DisassociateEntitiesRequest.prototype.ToSoapXml = function () {
                this.Parameters["Moniker1"] = this.Moniker1;
                this.Parameters["Moniker2"] = this.Moniker2;
                this.Parameters["RelationshipName"] = this.RelationshipName;
                return _super.prototype.ToSoapXml.call(this);
            };
            return DisassociateEntitiesRequest;
        })(Messages.OrganizationRequest);
        Messages.DisassociateEntitiesRequest = DisassociateEntitiesRequest;        
        var DisassociateEntitiesResponse = (function (_super) {
            __extends(DisassociateEntitiesResponse, _super);
            function DisassociateEntitiesResponse(responseXml) {
                        _super.call(this, "DisassociateEntities", responseXml);
            }
            return DisassociateEntitiesResponse;
        })(Messages.OrganizationResponse);
        Messages.DisassociateEntitiesResponse = DisassociateEntitiesResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../helpers.ts" />
    (function (Messages) {
        var ErrorResponse = (function () {
            function ErrorResponse(responseXml, responseText) {
                this.ResponseXml = responseXml;
                this.ResponseText = responseText;
                this.Error = "";
                this.ParseError();
            }
            ErrorResponse.prototype.ParseError = function () {
                if(this.ResponseXml.firstChild != null && this.ResponseXml.firstChild.firstChild) {
                    // todo: check that s:Fault is the right node and faultstring is the correct node, seen variations of this...
                    var fault = $Xrm._xml.getChildNode(this.ResponseXml.firstChild.firstChild, "s:Fault");
                    if(fault != null && fault != undefined) {
                        var faultTextNode = $Xrm._xml.getChildNode(fault, "faultstring");
                        if(faultTextNode != null && faultTextNode != undefined) {
                            this.Error = $Xrm._xml.getText(faultTextNode);
                        }
                        var detail = $Xrm._xml.getChildNode(fault, "detail");
                        if(detail != null && detail != undefined) {
                            var osf = $Xrm._xml.getChildNode(detail, "OrganizationServiceFault");
                            if(osf != null && osf != undefined) {
                                this.Error += $Xrm._string.format("\r\nOrganizationServiceFault.Message: {0}", $Xrm._xml.getText($Xrm._xml.getChildNode(osf, "Message")));
                                var inner = $Xrm._xml.getChildNode(osf, "InnerFault");
                                if(inner != null && inner != undefined) {
                                    this.Error += $Xrm._string.format("\r\nOrganizationServiceFault.InnerFault.Message: {0}", $Xrm._xml.getText($Xrm._xml.getChildNode(osf, "Message")));
                                }
                            }
                        }
                    }
                } else {
                    this.Error = this.ResponseText;
                }
            };
            return ErrorResponse;
        })();
        Messages.ErrorResponse = ErrorResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var ExecuteWorkflowRequest = (function (_super) {
            __extends(ExecuteWorkflowRequest, _super);
            function ExecuteWorkflowRequest() {
                        _super.call(this, "ExecuteWorkflow", "b");
                this.EntityId = null;
                this.WorkflowId = null;
            }
            ExecuteWorkflowRequest.prototype.GetResponse = function (responseXml) {
                return new ExecuteWorkflowResponse(responseXml);
            };
            ExecuteWorkflowRequest.prototype.ToSoapXml = function () {
                this.Parameters["EntityId"] = this.EntityId;
                this.Parameters["WorkflowId"] = this.WorkflowId;
                return _super.prototype.ToSoapXml.call(this);
            };
            return ExecuteWorkflowRequest;
        })(Messages.OrganizationRequest);
        Messages.ExecuteWorkflowRequest = ExecuteWorkflowRequest;        
        var ExecuteWorkflowResponse = (function (_super) {
            __extends(ExecuteWorkflowResponse, _super);
            function ExecuteWorkflowResponse(responseXml) {
                        _super.call(this, "ExecuteWorkflowResponse", responseXml);
                this.BindProperties();
            }
            ExecuteWorkflowResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.Id = this.Results["Id"];
            };
            return ExecuteWorkflowResponse;
        })(Messages.OrganizationResponse);
        Messages.ExecuteWorkflowResponse = ExecuteWorkflowResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var RetrieveMultipleRequest = (function (_super) {
            __extends(RetrieveMultipleRequest, _super);
            function RetrieveMultipleRequest(query) {
                        _super.call(this, "RetrieveMultiple");
                this.Query = query;
            }
            RetrieveMultipleRequest.prototype.GetResponse = function (responseXml) {
                return new RetrieveMultipleResponse(responseXml);
            };
            RetrieveMultipleRequest.prototype.ToSoapXml = function () {
                this.Parameters["Query"] = this.Query;
                return _super.prototype.ToSoapXml.call(this);
            };
            return RetrieveMultipleRequest;
        })(Messages.OrganizationRequest);
        Messages.RetrieveMultipleRequest = RetrieveMultipleRequest;        
        var RetrieveMultipleResponse = (function (_super) {
            __extends(RetrieveMultipleResponse, _super);
            function RetrieveMultipleResponse(responseXml) {
                        _super.call(this, "RetrieveMultiple", responseXml);
                this.ParseResponse(responseXml);
                this.BindProperties();
            }
            RetrieveMultipleResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.Entities = this.Results["Entities"];
            };
            RetrieveMultipleResponse.prototype.ParseResponse = function (responseXml) {
                this.Results = [];
                var rn = $Xrm._xml.getChildNode(responseXml.firstChild.firstChild.firstChild.firstChild, 'a:Results');
                if(rn != null) {
                    var entities = $Xrm._xml.getChildNode(rn.firstChild, 'b:value');
                    if(entities != null && entities.firstChild != null && entities.firstChild.childNodes != null) {
                        var resultsNode = entities.firstChild.childNodes;
                        var parsed = RetrieveMultipleResponse.ParseResults(resultsNode);
                        this.Results["Entities"] = parsed;
                    }
                }
            };
            RetrieveMultipleResponse.GetValueFromXml = function GetValueFromXml(type, valueNode) {
                switch(type) {
                    case "a:OptionSetValue":
                        return new $Xrm.OptionSetValue(parseInt($Xrm._xml.getText(valueNode)));
                    case "a:EntityReference":
                        var ref = new $Xrm.EntityReference();
                        ref.Id = $Xrm._xml.getText(valueNode.childNodes[0]);
                        ref.LogicalName = $Xrm._xml.getText(valueNode.childNodes[1]);
                        ref.Name = $Xrm._xml.getText(valueNode.childNodes[2]);
                        return ref;
                    case "a:Money":
                        var value = parseFloat($Xrm._xml.getText(valueNode.childNodes[0]));
                        return new $Xrm.Money(value);
                    case "a:AliasedValue":
                        valueNode = $Xrm._xml.getChildNode(valueNode, "a:Value");
                        type = $Xrm._xml.getText($Xrm._xml.getAttribute(valueNode, "i:type"));
                        return RetrieveMultipleResponse.GetValueFromXml(type, valueNode);
                    default:
                        return $Xrm._xml.getText(valueNode);
                }
            };
            RetrieveMultipleResponse.ParseResults = function ParseResults(resultsNode) {
                var results = new Array(resultsNode.length);
                for(var i = 0; i < results.length; i++) {
                    var node = resultsNode[i];
                    var je = new $Xrm.Entity("");
                    //var o = new Array();
                    for(var j = 0; j < node.childNodes.length; j++) {
                        switch(node.childNodes[j].nodeName) {
                            case "a:Attributes":
                                var attr = node.childNodes[j];
                                for(var k = 0; k < attr.childNodes.length; k++) {
                                    var key = $Xrm._xml.getText(attr.childNodes[k].firstChild);
                                    var type = "";
                                    for(var l = 0; l < attr.childNodes[k].childNodes[1].attributes.length; l++) {
                                        if(attr.childNodes[k].childNodes[1].attributes[l].nodeName == "i:type") {
                                            type = $Xrm._xml.getText(attr.childNodes[k].childNodes[1].attributes[l]);
                                        }
                                    }
                                    var valueNode = attr.childNodes[k].childNodes[1];
                                    var value = RetrieveMultipleResponse.GetValueFromXml(type, valueNode);
                                    je[key] = value;
                                }
                                break;
                            case "a:Id":
                                je.Id = $Xrm._xml.getText(node.childNodes[j]);
                                break;
                            case "a:LogicalName":
                                je.LogicalName = $Xrm._xml.getText(node.childNodes[j]);
                                break;
                            case "a:FormattedValues":
                                var foVal = node.childNodes[j];
                                for(var k = 0; k < foVal.childNodes.length; k++) {
                                    var key = $Xrm._xml.getText(foVal.childNodes[k].firstChild);
                                    je[key].FormattedValue = $Xrm._xml.getText(foVal.childNodes[k].childNodes[1]);
                                }
                                break;
                        }
                    }
                    results[i] = je;
                }
                return results;
            };
            return RetrieveMultipleResponse;
        })(Messages.OrganizationResponse);
        Messages.RetrieveMultipleResponse = RetrieveMultipleResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    /// <reference path="retrievemultiple.ts" />
    (function (Messages) {
        var RetrieveRequest = (function (_super) {
            __extends(RetrieveRequest, _super);
            // can be true or array of columns (true = all columns)
            function RetrieveRequest(target, columnSet) {
                        _super.call(this, "Retrieve");
                this.Target = target;
                this.ColumnSet = columnSet;
            }
            RetrieveRequest.prototype.GetResponse = function (responseXml) {
                return new RetrieveResponse(responseXml);
            };
            RetrieveRequest.prototype.ToSoapXml = function () {
                this.Parameters["Target"] = this.Target;
                this.Parameters["ColumnSet"] = this.ColumnSet;
                return _super.prototype.ToSoapXml.call(this);
            };
            return RetrieveRequest;
        })(Messages.OrganizationRequest);
        Messages.RetrieveRequest = RetrieveRequest;        
        var RetrieveResponse = (function (_super) {
            __extends(RetrieveResponse, _super);
            function RetrieveResponse(responseXml) {
                        _super.call(this, "Retrieve", responseXml);
                this.ParseResponse(responseXml);
                this.BindProperties();
            }
            RetrieveResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.Entity = this.Results["Entity"];
            };
            RetrieveResponse.prototype.ParseResponse = // retrieve result is tricky, can't use the standard parser inside organization.ts
            function (responseXml) {
                this.Results = []// clear the values parsed from the base class
                ;
                var rn = $Xrm._xml.getChildNode(responseXml.firstChild.firstChild.firstChild.firstChild, 'a:Results');
                if(rn != null && rn.firstChild != null) {
                    var entities = rn.firstChild;
                    if(entities != null && entities.childNodes.length > 1) {
                        var resultsNode = entities.childNodes;
                        var parsed = Messages.RetrieveMultipleResponse.ParseResults(resultsNode);
                        if(parsed.length > 1) {
                            this.Results["Entity"] = parsed[1]// the 1st one has a dummy record due to us reusing retrievemultiple parser
                            ;
                        }
                    }
                }
            };
            return RetrieveResponse;
        })(Messages.OrganizationResponse);
        Messages.RetrieveResponse = RetrieveResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var RetrieveEntityRequest = (function (_super) {
            __extends(RetrieveEntityRequest, _super);
            function RetrieveEntityRequest() {
                        _super.call(this, "RetrieveEntity");
                this.EntityFilters = null;
                this.MetadataId = "00000000-0000-0000-0000-000000000000";
                this.RetrieveAsIfPublished = true;
                this.LogicalName = null;
            }
            RetrieveEntityRequest.prototype.GetResponse = function (responseXml) {
                return new RetrieveEntityResponse(responseXml);
            };
            RetrieveEntityRequest.prototype.ToSoapXml = function () {
                this.Parameters["EntityFilters"] = this.EntityFilters;
                this.Parameters["MetadataId"] = this.MetadataId;
                this.Parameters["RetrieveAsIfPublished"] = this.RetrieveAsIfPublished;
                this.Parameters["LogicalName"] = this.LogicalName;
                return _super.prototype.ToSoapXml.call(this);
            };
            return RetrieveEntityRequest;
        })(Messages.OrganizationRequest);
        Messages.RetrieveEntityRequest = RetrieveEntityRequest;        
        var RetrieveEntityResponse = (function (_super) {
            __extends(RetrieveEntityResponse, _super);
            function RetrieveEntityResponse(responseXml) {
                        _super.call(this, "RetrieveEntity", responseXml);
                this.ParseResponse(responseXml);
                this.BindProperties();
            }
            RetrieveEntityResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.EntityMetadata = this.Results["EntityMetadata"];
            };
            RetrieveEntityResponse.prototype.ParseResponse = function (responseXml) {
                this.Results = []// clear the values parsed from the base class
                ;
                var rn = $Xrm._xml.getChildNode(responseXml.firstChild.firstChild.firstChild.firstChild, 'a:Results');
                if(rn != null && rn.firstChild != null) {
                    var entities = rn.firstChild;// KeyValuePairOfstringanyType
                    
                    if(entities != null && entities.childNodes.length > 1) {
                        var keyvalues = entities.childNodes;
                        var key = $Xrm._xml.getText(keyvalues[0]);
                        var value = keyvalues[1];
                        var metadata = new $Xrm.EntityMetadata();
                        this.ParseNested(value, metadata);
                        this.Results[key] = metadata;
                    }
                }
            };
            RetrieveEntityResponse.prototype.ParseNested = function (node, metadataField) {
                if(node.childNodes != null && node.childNodes != undefined && node.childNodes.length > 1) {
                    for(var i = 0; i < node.childNodes.length; i++) {
                        var current = node.childNodes[i];
                        var nodeName = $Xrm._xml.stripNamespace(current.nodeName);
                        // these guys get special treatment :)
                        if(nodeName == "AttributeMetadata") {
                            nodeName = $Xrm._xml.getText($Xrm._xml.getChildNode(current, "c:LogicalName"));
                        } else if(nodeName == "ManyToManyRelationshipMetadata" || nodeName == "ManyToOneRelationshipMetadata" || nodeName == "OneToManyRelationshipMetadata") {
                            nodeName = $Xrm._xml.getText($Xrm._xml.getChildNode(current, "c:SchemaName"));
                        } else if(nodeName == "Privileges") {
                            nodeName = $Xrm._xml.getText($Xrm._xml.getChildNode(current, "c:Name"));
                        }
                        if(nodeName != null) {
                            metadataField[nodeName] = new Object();
                            if(current.childNodes != null && current.childNodes != undefined && current.childNodes.length > 1) {
                                this.ParseNested(current, metadataField[nodeName]);
                            } else {
                                metadataField[nodeName] = $Xrm._xml.getValue(current);
                            }
                        }
                    }
                } else {
                    var nodeName = $Xrm._xml.stripNamespace(node.nodeName);
                    metadataField[nodeName] = $Xrm._xml.getValue(node);
                }
            };
            return RetrieveEntityResponse;
        })(Messages.OrganizationResponse);
        Messages.RetrieveEntityResponse = RetrieveEntityResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var SendEmailRequest = (function (_super) {
            __extends(SendEmailRequest, _super);
            function SendEmailRequest() {
                        _super.call(this, "SendEmail", "b");
                this.EmailId = null;
                this.IssueSend = null;
                this.TrackingToken = "";
            }
            SendEmailRequest.prototype.GetResponse = function (responseXml) {
                return new SendEmailResponse(responseXml);
            };
            SendEmailRequest.prototype.ToSoapXml = function () {
                this.Parameters["EmailId"] = this.EmailId;
                this.Parameters["IssueSend"] = this.IssueSend;
                this.Parameters["TrackingToken"] = this.TrackingToken;
                return _super.prototype.ToSoapXml.call(this);
            };
            return SendEmailRequest;
        })(Messages.OrganizationRequest);
        Messages.SendEmailRequest = SendEmailRequest;        
        var SendEmailResponse = (function (_super) {
            __extends(SendEmailResponse, _super);
            function SendEmailResponse(responseXml) {
                        _super.call(this, "SendEmail", responseXml);
                this.BindProperties();
            }
            SendEmailResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.Subject = this.Results["Subject"];
            };
            return SendEmailResponse;
        })(Messages.OrganizationResponse);
        Messages.SendEmailResponse = SendEmailResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var SetStateRequest = (function (_super) {
            __extends(SetStateRequest, _super);
            function SetStateRequest() {
                        _super.call(this, "SetState", "b")// namespace is 'b' because this request is from crm4 days
                ;
                this.EntityMoniker = null;
                this.State = null;
                this.Status = null;
            }
            SetStateRequest.prototype.GetResponse = function (responseXml) {
                return new SetStateResponse(responseXml);
            };
            SetStateRequest.prototype.ToSoapXml = function () {
                this.Parameters["EntityMoniker"] = this.EntityMoniker;
                this.Parameters["State"] = this.State;
                this.Parameters["Status"] = this.Status;
                return _super.prototype.ToSoapXml.call(this);
            };
            return SetStateRequest;
        })(Messages.OrganizationRequest);
        Messages.SetStateRequest = SetStateRequest;        
        var SetStateResponse = (function (_super) {
            __extends(SetStateResponse, _super);
            function SetStateResponse(responseXml) {
                        _super.call(this, "SetState", responseXml);
            }
            return SetStateResponse;
        })(Messages.OrganizationResponse);
        Messages.SetStateResponse = SetStateResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var UpdateRequest = (function (_super) {
            __extends(UpdateRequest, _super);
            function UpdateRequest() {
                        _super.call(this, "Update");
                this.Target = null;
            }
            UpdateRequest.prototype.GetResponse = function (responseXml) {
                return new UpdateResponse(responseXml);
            };
            UpdateRequest.prototype.ToSoapXml = function () {
                this.Parameters["Target"] = this.Target;
                return _super.prototype.ToSoapXml.call(this);
            };
            return UpdateRequest;
        })(Messages.OrganizationRequest);
        Messages.UpdateRequest = UpdateRequest;        
        var UpdateResponse = (function (_super) {
            __extends(UpdateResponse, _super);
            function UpdateResponse(responseXml) {
                        _super.call(this, "Update", responseXml);
            }
            return UpdateResponse;
        })(Messages.OrganizationResponse);
        Messages.UpdateResponse = UpdateResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
var $Xrm;
(function ($Xrm) {
    /// <reference path="../types.ts" />
    /// <reference path="../helpers.ts" />
    /// <reference path="organization.ts" />
    (function (Messages) {
        var WhoAmIRequest = (function (_super) {
            __extends(WhoAmIRequest, _super);
            function WhoAmIRequest() {
                        _super.call(this, "WhoAmI", "b");
            }
            WhoAmIRequest.prototype.GetResponse = function (responseXml) {
                return new WhoAmIResponse(responseXml);
            };
            WhoAmIRequest.prototype.ToSoapXml = function () {
                return _super.prototype.ToSoapXml.call(this);
            };
            return WhoAmIRequest;
        })(Messages.OrganizationRequest);
        Messages.WhoAmIRequest = WhoAmIRequest;        
        var WhoAmIResponse = (function (_super) {
            __extends(WhoAmIResponse, _super);
            function WhoAmIResponse(responseXml) {
                        _super.call(this, "WhoAmI", responseXml);
                this.BindProperties();
            }
            WhoAmIResponse.prototype.BindProperties = function () {
                _super.prototype.BindProperties.call(this);
                this.UserId = this.Results["UserId"];
                this.BusinessUnitId = this.Results["BusinessUnitId"];
                this.OrganizationId = this.Results["OrganizationId"];
            };
            return WhoAmIResponse;
        })(Messages.OrganizationResponse);
        Messages.WhoAmIResponse = WhoAmIResponse;        
    })($Xrm.Messages || ($Xrm.Messages = {}));
    var Messages = $Xrm.Messages;
})($Xrm || ($Xrm = {}));
/// <reference path="Helpers.ts" />
/// <reference path="Types.ts" />
/// <reference path="messages/Assign.ts" />
/// <reference path="messages/AssociatEentities.ts" />
/// <reference path="messages/Create.ts" />
/// <reference path="messages/DisassociateEntities.ts" />
/// <reference path="messages/Error.ts" />
/// <reference path="messages/ExecuteWorkflow.ts" />
/// <reference path="messages/Organization.ts" />
/// <reference path="messages/Retrieve.ts" />
/// <reference path="messages/RetrieveEntity.ts" />
/// <reference path="messages/RetrieveMultiple.ts" />
/// <reference path="messages/SendEmail.ts" />
/// <reference path="messages/SetState.ts" />
/// <reference path="messages/Update.ts" />
/// <reference path="messages/WhoAmI.ts" />
var $Xrm;
(function ($Xrm) {
    var OrganizationService = (function () {
        function OrganizationService(sdkUrl) {
            this._sdkUrl = sdkUrl;
        }
        OrganizationService.prototype.Associate = function (moniker1, moniker2, relationshipName) {
            var ar = new $Xrm.Messages.AssociateEntitiesRequest();
            ar.Moniker1 = moniker1;
            ar.Moniker2 = moniker2;
            ar.RelationshipName = relationshipName;
            this.Execute(ar);
        };
        OrganizationService.prototype.AssociateAsync = function (moniker1, moniker2, relationshipName, callback) {
            var ar = new $Xrm.Messages.AssociateEntitiesRequest();
            ar.Moniker1 = moniker1;
            ar.Moniker2 = moniker2;
            ar.RelationshipName = relationshipName;
            this.ExecuteAsync(ar, function (response) {
                if(response != null && response != undefined) {
                    if(callback != null) {
                        callback();
                    }
                }
            });
        };
        OrganizationService.prototype.Disassociate = function (moniker1, moniker2, relationshipName) {
            var ar = new $Xrm.Messages.DisassociateEntitiesRequest();
            ar.Moniker1 = moniker1;
            ar.Moniker2 = moniker2;
            ar.RelationshipName = relationshipName;
            this.Execute(ar);
        };
        OrganizationService.prototype.DisassociateAsync = function (moniker1, moniker2, relationshipName, callback) {
            var ar = new $Xrm.Messages.DisassociateEntitiesRequest();
            ar.Moniker1 = moniker1;
            ar.Moniker2 = moniker2;
            ar.RelationshipName = relationshipName;
            this.ExecuteAsync(ar, function (response) {
                if(response != null && response != undefined) {
                    if(callback != null) {
                        callback();
                    }
                }
            });
        };
        OrganizationService.prototype.Create = function (entity) {
            var cr = new $Xrm.Messages.CreateRequest();
            cr.Target = entity;
            var response = this.Execute(cr);
            if(response != null && response != undefined) {
                return response.Id;
            }
            return null;
        };
        OrganizationService.prototype.CreateAsync = function (entity, callback) {
            var cr = new $Xrm.Messages.CreateRequest();
            cr.Target = entity;
            this.ExecuteAsync(cr, function (response) {
                if(response != null && response != undefined) {
                    if(callback != null) {
                        callback(response.Id);
                    }
                }
            });
        };
        OrganizationService.prototype.Update = function (entity) {
            var ur = new $Xrm.Messages.UpdateRequest();
            ur.Target = entity;
            var response = this.Execute(ur);
        };
        OrganizationService.prototype.UpdateAsync = function (entity, callback) {
            var ur = new $Xrm.Messages.UpdateRequest();
            ur.Target = entity;
            this.ExecuteAsync(ur, function (response) {
                if(response != null && response != undefined) {
                    if(callback != null) {
                        callback();
                    }
                }
            });
        };
        OrganizationService.prototype.Retrieve = function (entityName, id, columnSet) {
            if(columnSet == null || columnSet == undefined) {
                columnSet = true;
            }
            var rr = new $Xrm.Messages.RetrieveRequest();
            rr.Target = new $Xrm.EntityReference(entityName, id);
            rr.ColumnSet = columnSet;
            var response = this.Execute(rr);
            if(response != null && response != undefined) {
                return response.Entity;
            }
            return null;
        };
        OrganizationService.prototype.RetrieveAsync = function (entityName, id, columnSet, callback) {
            if(columnSet == null || columnSet == undefined) {
                columnSet = true;
            }
            var rr = new $Xrm.Messages.RetrieveRequest();
            rr.Target = new $Xrm.EntityReference(entityName, id);
            rr.ColumnSet = columnSet;
            this.ExecuteAsync(rr, function (response) {
                if(response != null && response != undefined) {
                    if(callback != null) {
                        callback(response.Entity);
                    }
                }
            });
        };
        OrganizationService.prototype.RetrieveMultiple = function (fetchXml) {
            var rmr = new $Xrm.Messages.RetrieveMultipleRequest();
            rmr.Query = new $Xrm.FetchExpression(this.Encode(fetchXml));
            var response = this.Execute(rmr);
            if(response != null && response != undefined) {
                return response.Entities;
            }
            return null;
        };
        OrganizationService.prototype.RetrieveMultipleAsync = function (fetchXml, callback) {
            var rmr = new $Xrm.Messages.RetrieveMultipleRequest();
            rmr.Query = new $Xrm.FetchExpression(this.Encode(fetchXml));
            this.ExecuteAsync(rmr, function (response) {
                if(response != null && response != undefined) {
                    if(callback != null) {
                        callback(response.Entities);
                    }
                }
            });
        };
        OrganizationService.prototype.Delete = // todo: convert these to DeleteRequest/Response messages to keep it consistant with others
        function (entityName, id) {
            var request = this.ExecuteAjaxRequest("Delete", $Xrm._string.format('<entityName>{0}</entityName><id>{1}</id>', entityName, id), false);
        };
        OrganizationService.prototype.DeleteAsync = function (entityName, id, callback) {
            this.ExecuteAjaxRequest("Delete", $Xrm._string.format('<entityName>{0}</entityName><id>{1}</id>', entityName, id), true, function (request) {
                if(callback != null) {
                    callback();
                }
            });
        };
        OrganizationService.prototype.Execute = function (request) {
            var response = this.ExecuteAjaxRequest("Execute", request.ToSoapXml(), false);
            if(response != null && response != undefined) {
                return request.GetResponse(response.responseXML);
            }
            return null;
        };
        OrganizationService.prototype.ExecuteAsync = function (request, callback) {
            var response = this.ExecuteAjaxRequest("Execute", request.ToSoapXml(), true, function (r) {
                if(r != null && r != undefined) {
                    if(callback != null) {
                        callback(request.GetResponse(r.responseXML));
                    }
                }
            });
        };
        OrganizationService.prototype.WashWithSoapHeader = function (operation, requestXml) {
            return $Xrm._string.format('<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><{0} xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">{1}</{0}></s:Body></s:Envelope>', operation, requestXml);
        };
        OrganizationService.prototype.ExecuteAjaxRequest = function (operation, requestXml, async, callback) {
            requestXml = this.WashWithSoapHeader(operation, requestXml);
            var request = new XMLHttpRequest();
            request.open("POST", this._sdkUrl + "/XRMServices/2011/Organization.svc/web", async);
            request.setRequestHeader("Accept", "application/xml, text/xml, */*");
            request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
            request.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/" + operation);
            if(async) {
                request.onreadystatechange = function () {
                    if(request.readyState == 4) {
                        if(request.status == 200) {
                            callback(request);
                        } else {
                            throw new $Xrm.Messages.ErrorResponse(request.responseXML, request.responseText);
                        }
                    }
                };
                request.send(requestXml);
            } else {
                request.send(requestXml);
                if(request.status != 200) {
                    throw new $Xrm.Messages.ErrorResponse(request.responseXML, request.responseText);
                }
                return request;
            }
            return null;
        };
        OrganizationService.prototype.Encode = function (xml) {
            return xml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        };
        return OrganizationService;
    })();
    $Xrm.OrganizationService = OrganizationService;    
})($Xrm || ($Xrm = {}));
